package com.sqx.modules.pay.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sqx.common.utils.PageUtils;
import com.sqx.common.utils.Query;
import com.sqx.common.utils.Result;
import com.sqx.modules.app.dao.UserCashOutDao;
import com.sqx.modules.app.dao.UserDao;
import com.sqx.modules.app.dao.UserMoneyDao;
import com.sqx.modules.app.dao.UserMoneyDetailsDao;
import com.sqx.modules.app.entity.UserEntity;
import com.sqx.modules.app.entity.UserMoney;
import com.sqx.modules.app.entity.UserMoneyDetails;
import com.sqx.modules.app.service.UserMoneyDetailsService;
import com.sqx.modules.app.service.UserService;
import com.sqx.modules.common.entity.CommonInfo;
import com.sqx.modules.common.service.CommonInfoService;
import com.sqx.modules.errand.dao.ErrandComplaintDao;
import com.sqx.modules.errand.dao.TbIndentDao;
import com.sqx.modules.errand.entity.ErrandComplaint;
import com.sqx.modules.errand.entity.TbIndent;
import com.sqx.modules.message.dao.MessageInfoDao;
import com.sqx.modules.message.entity.MessageInfo;
import com.sqx.modules.pay.dao.CashOutDao;
import com.sqx.modules.pay.entity.CashOut;
import com.sqx.modules.pay.service.CashOutService;
import com.sqx.modules.sys.dao.SysUserDao;
import com.sqx.modules.utils.AmountCalUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import weixin.popular.api.MessageAPI;
import weixin.popular.bean.message.templatemessage.TemplateMessage;
import weixin.popular.bean.message.templatemessage.TemplateMessageItem;
import weixin.popular.bean.message.templatemessage.TemplateMessageResult;
import weixin.popular.support.TokenManager;

import javax.websocket.SendResult;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 提现申请记录
 */
@Service
public class CashOutServiceImpl extends ServiceImpl<CashOutDao, CashOut> implements CashOutService {

    /**
     * 提现申请记录
     */
    @Autowired
    private CashOutDao cashOutDao;
    /**
     * 通用配置
     */
    @Autowired
    private CommonInfoService commonInfoService;
    /**
     * app用户
     */
    @Autowired
    private UserService userService;
    @Autowired
    private MessageInfoDao messageInfoDao;
    @Autowired
    private UserCashOutDao userCashOutDao;
    @Autowired
    private UserMoneyDetailsDao userMoneyDetailsDao;
    @Autowired
    private UserMoneyDao userMoneyDao;
    @Autowired
    private ErrandComplaintDao errandComplaintDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private TbIndentDao tbIndentDao;
    @Autowired
    private ErrandComplaintDao complaintDao;
    @Autowired
    private SysUserDao sysUserDao;
    @Autowired
    private UserMoneyDetailsService userMoneyDetailsService;
    private ReentrantReadWriteLock reentrantReadWriteLock = new ReentrantReadWriteLock(true);

    @Override
    public PageUtils selectCashOutList(Map<String, Object> params) {
        String zhifubaoName = (String) params.get("zhifubaoName");
        String zhifubao = (String) params.get("zhifubao");
        String userId = String.valueOf(params.get("userId"));
        String type = String.valueOf(params.get("type"));
        String state = String.valueOf(params.get("state"));
        String phone = String.valueOf(params.get("phone"));
        IPage<CashOut> page = this.page(
                new Query<CashOut>().getPage(params),
                new QueryWrapper<CashOut>()
                        .eq(StringUtils.isNotBlank(zhifubaoName) && !"null".equals(zhifubaoName), "zhifubao_name", zhifubaoName)
                        .eq(StringUtils.isNotBlank(zhifubao) && !"null".equals(zhifubao), "zhifubao", zhifubao)
                        .eq(StringUtils.isNotBlank(userId) && !"null".equals(userId), "user_id", userId)
                        .eq(StringUtils.isNotBlank(type) && !"null".equals(type), "type", type)
                        .eq(StringUtils.isNotBlank(state) && !"null".equals(state), "state", state)
                        .like(StringUtils.isNotBlank(phone) && !"null".equals(phone), "phone", phone)
                        .orderByDesc("id")
        );
        return new PageUtils(page);
    }


    @Override
    public CashOut selectById(Long id) {
        return cashOutDao.selectById(id);
    }

    @Override
    public int saveBody(CashOut cashOut) {
        return cashOutDao.insert(cashOut);
    }


    @Override
    public int update(CashOut cashOut) {
        return cashOutDao.updateById(cashOut);
    }


    @Override
    public void cashOutSuccess(UserEntity userByWxId, String date, String money, String payWay, String url) {
        if (userByWxId != null) {
            MessageInfo messageInfo = new MessageInfo();
            messageInfo.setState(String.valueOf(5));
            messageInfo.setContent("您好，您的提现转账成功，请注意查收！提现金额【" + money + "元】！感谢您的使用！如有疑问请在公众号中发送您的问题联系客服");
            messageInfo.setTitle("提现成功通知");
            messageInfo.setUserName(userByWxId.getUserName());
            messageInfo.setUserId(String.valueOf(userByWxId.getUserId()));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date now = new Date();
            messageInfo.setCreateAt(sdf.format(now));
            messageInfo.setIsSee("0");
            messageInfoDao.insert(messageInfo);
            if (userByWxId.getClientid() != null) {
                userService.pushToSingle("提现成功通知", "您好，您的提现转账成功，请注意查收！提现金额【" + money + "元】！感谢您的使用！如有疑问请在公众号中发送您的问题联系客服", userByWxId.getClientid());
            }
            CommonInfo three = commonInfoService.findOne(39);
            String apkey = "";
            if (three != null) {
                apkey = three.getValue();
            }
            if (StringUtils.isNotBlank(userByWxId.getOpenId())) {
                LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
                data.put("first", new TemplateMessageItem("您好，您的提现转账成功，请注意查收", "#d71345"));
                data.put("keyword1", new TemplateMessageItem(money + " 元", "#d71345"));
                data.put("keyword2", new TemplateMessageItem(date, "#d71345"));
                data.put("remark", new TemplateMessageItem("感谢您的使用！如有疑问请在公众号中发送您的问题联系客服", null));
                sendWxMessage(apkey, data, userByWxId.getOpenId(), url);
            }
        }

    }

    /**
     * 退款成功通知
     *
     * @param
     * @param date
     * @param money
     * @param url
     */
    @Override
    public void refundSuccess(UserEntity userByWxId, String date, String money, String url, String content) {
        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setState(String.valueOf(5));
        messageInfo.setContent(content);
        messageInfo.setTitle("提现失败提醒");
        messageInfo.setUserName(userByWxId.getUserName());
        messageInfo.setUserId(String.valueOf(userByWxId.getUserId()));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date now = new Date();
        messageInfo.setCreateAt(sdf.format(now));
        messageInfo.setIsSee("0");
        messageInfoDao.insert(messageInfo);
        if (userByWxId.getClientid() != null) {
            userService.pushToSingle("提现失败提醒", content, userByWxId.getClientid());
        }
        CommonInfo three = commonInfoService.findOne(77);
        String apkey = "";
        if (three != null) {
            apkey = three.getValue();
        }
        if (StringUtils.isNotBlank(userByWxId.getOpenId())) {
            LinkedHashMap<String, TemplateMessageItem> data = new LinkedHashMap<>();
            data.put("first", new TemplateMessageItem("您好，您发起的提现失败了", "#d71345"));
            data.put("keyword1", new TemplateMessageItem(money + " 元", "#d71345"));
            data.put("keyword2", new TemplateMessageItem(date, "#d71345"));
            data.put("keyword3", new TemplateMessageItem(content, "#d71345"));
            data.put("remark", new TemplateMessageItem("请您按照失败原因修改相关信息后，重新提现！", null));
            sendWxMessage(apkey, data, userByWxId.getOpenId(), url);
        }

    }

    @Override
    public Double selectCashOutSum(Long userId, Date startTime, Date endTime) {
        return cashOutDao.selectCashOutSum(userId, startTime, endTime);
    }

    @Override
    public Double selectCashOutSumsByNowMonth(Long userId) {
        return cashOutDao.selectCashOutSumsByNowMonth(userId);
    }

    /*@Override
    public Double sumMoney(String time, Integer flag) {
        return cashOutDao.sumMoney(time, flag);
    }*/

    /*@Override
    public Integer countMoney(String time, Integer flag) {
        return cashOutDao.countMoney(time, flag);
    }*/

    /*@Override
    public Integer stayMoney(String time, Integer flag) {
        return cashOutDao.stayMoney(time, flag);
    }*/

    @Override
    public void updateMayMoney(int i, Long userId, Double money) {
        cashOutDao.updateMayMoney(i, userId, money);
    }


    @Override
    public List<CashOut> selectCashOutLimit3() {
        return cashOutDao.selectCashOutLimit3();
    }

    private void sendWxMessage(String templateId, LinkedHashMap<String, TemplateMessageItem> data, String openid, String url) {
        TemplateMessage templateMessage = new TemplateMessage();
        templateMessage.setTouser(openid);
        templateMessage.setTemplate_id(templateId);
        templateMessage.setData(data);
        templateMessage.setUrl(url);
        TemplateMessageResult templateMessageResult = MessageAPI.messageTemplateSend(getWxToken(), templateMessage);
        if (templateMessageResult.isSuccess()) {
            new SendResult();
        } else {
            new SendResult();
        }
    }

    private String getWxToken() {
        try {
            //微信appid
            CommonInfo one = commonInfoService.findOne(5);
            return TokenManager.getToken(one.getValue());
        } catch (Exception e) {
            throw new RuntimeException("GET_ACCESS_TOKEN_FAIL");
        }
    }


    @Override
    @Transactional
    public Result cashMoney(Long userId, Long shopId, Double money, Integer classify, Integer type) {

        return cashMoneys(userId, shopId, money, classify, type);
    }

    @Override
    public Result statisticsMoney(String date, String dateType, Integer type) {
        HashMap hashMap = new HashMap();
        BigDecimal sumMoney = cashOutDao.sumMoney(date, dateType, null, type);
        Integer countMoney = cashOutDao.countMoney(date, dateType, null, type);
        Integer stayMoney = cashOutDao.stayMoney(date, dateType, type);
        BigDecimal sumMoneySucceed = cashOutDao.sumMoney(date, dateType, 1, type);
        Integer countMoneySucceed = cashOutDao.countMoney(date, dateType, 1, type);
        BigDecimal sumMoneyAwait = cashOutDao.sumMoney(date, dateType, 0, type);
        BigDecimal applyMoneySum = cashOutDao.applyMoneySum(date, dateType, type);
        BigDecimal accomplishMoneySum = cashOutDao.accomplishMoneySum(date, dateType, type);
        BigDecimal refuseMoneySum = cashOutDao.refuseMoneySum(date, dateType, type);
        BigDecimal zhifubaoMoneySum = cashOutDao.zhifubaoMoneySum(date, dateType, type);
        BigDecimal weixinMoneySum = cashOutDao.weixinMoneySum(date, dateType, type);
        BigDecimal cashDepositMoneySum = cashOutDao.cashDepositMoneySum(date, dateType);
        hashMap.put("sumMoney", sumMoney);//累计提现
        hashMap.put("countMoney", countMoney);//提现次数
        hashMap.put("stayMoney", stayMoney);//带转账次数
        hashMap.put("sumMoneySucceed", sumMoneySucceed);//提现成功总金额
        hashMap.put("countMoneySucceed", countMoneySucceed);//提现成功笔数
        hashMap.put("sumMoneyAwait", sumMoneyAwait);//待提现总金额
        hashMap.put("applyMoneySum", applyMoneySum);//申请提现金额
        hashMap.put("accomplishMoneySum", accomplishMoneySum);//已转账金额
        hashMap.put("refuseMoneySum", refuseMoneySum);//已拒绝金额
        hashMap.put("zhifubaoMoneySum", zhifubaoMoneySum);//支付宝提现金额
        hashMap.put("weixinMoneySum", weixinMoneySum);//微信提现金额
        hashMap.put("cashDepositMoneySum", cashDepositMoneySum);//保证金退款金额
        return Result.success().put("data", hashMap);
    }

    @Override
    public Result incomeStatistics(String date, String dateType) {
        HashMap hashMap = new HashMap();
        //扣除骑手保证金收入
        BigDecimal deductMoneySum = errandComplaintDao.deductMoneySum(date, dateType);
        //保价费收入
        BigDecimal cargoInsurance = cashOutDao.cargoInsurance(date, dateType);
        //帮我送收入
        BigDecimal firstMoneySum = cashOutDao.MoneySumByIndentType(date, dateType, "1");
        //帮我取收入
        BigDecimal secondMoneySum = cashOutDao.MoneySumByIndentType(date, dateType, "2");
        //帮我买收入
        BigDecimal thirdMoneySum = cashOutDao.MoneySumByIndentType(date, dateType, "3");
        //同城服务收入
        BigDecimal fourthMoneySum = cashOutDao.MoneySumByIndentType(date, dateType, "4");
        //服务费=四项总收入
        BigDecimal serviceSum = firstMoneySum.add(secondMoneySum).add(thirdMoneySum).add(fourthMoneySum);
        //总收入=服务费+保价费+扣除骑手保证金
        BigDecimal allSum = serviceSum.add(cargoInsurance).add(deductMoneySum);
        //骑手保证金收入
        BigDecimal cashDepositMoney = cashOutDao.cashDepositMoney(date, dateType);

        /*//平台总收入=总收入-商品费
        BigDecimal allMoneySum = cashOutDao.allMoneySum(date, dateType);
        BigDecimal prepayMoney = cashOutDao.allPrepayMoney(date, dateType);
        BigDecimal subtract = allMoneySum.subtract(prepayMoney);
        BigDecimal add = subtract.add(deductMoneySum);
        //服务费收入
        BigDecimal serviceMoneySum = cashOutDao.serviceMoneySum(date, dateType);
        BigDecimal subtract1 = serviceMoneySum.subtract(cargoInsurance);*/

        hashMap.put("allMoneySum", allSum);
        hashMap.put("serviceMoneySum", serviceSum);
        hashMap.put("firstMoneySum", firstMoneySum);
        hashMap.put("secondMoneySum", secondMoneySum);
        hashMap.put("thirdMoneySum", thirdMoneySum);
        hashMap.put("fourthMoneySum", fourthMoneySum);
        hashMap.put("cashDepositMoney", cashDepositMoney);
        hashMap.put("cargoInsurance", cargoInsurance);
        hashMap.put("deductMoneySum", deductMoneySum);
        return Result.success().put("data", hashMap);
    }

    @Transactional
    public Result cashMoneys(Long userId, Long shopId, Double money, Integer classify, Integer type) {
        reentrantReadWriteLock.writeLock().lock();
        try {

            if (money == null || money <= 0.00) {
                return Result.error("请不要输入小于0的数字,请输入正确的提现金额！");
            }
            //最低提现金额
            CommonInfo one = commonInfoService.findOne(112);
            if (one != null && money < Double.parseDouble(one.getValue())) {
                return Result.error("输入金额不满足最低提现金额，请重新输入！");
            }
            //最高提现金额
            CommonInfo one2 = commonInfoService.findOne(153);
            if (one2 != null && money > Double.parseDouble(one2.getValue())) {
                return Result.error(-100, "输入金额过大，不能大于" + one2.getValue() + "，请重新输入！");
            }
            //手续费
            Double mul = 0.0;
            String isRate = commonInfoService.findOne(116).getValue();

            if (type == 1) {
                //用户提现手续费
                CommonInfo one1 = commonInfoService.findOne(114);
                Double value = Double.valueOf(one1.getValue());
                mul = AmountCalUtils.mul(money, value);
                //计算提现金额所需要的手续费  小于0.01 的按0.01来算
                if (mul < 0.01) {
                    mul = 0.01;
                }
            } else {
                if ("是".equals(isRate)) {
                    //商户提现手续费
                    CommonInfo one1 = commonInfoService.findOne(115);
                    Double value = Double.valueOf(one1.getValue());
                    mul = AmountCalUtils.mul(money, value);
                    //计算提现金额所需要的手续费  小于0.01 的按0.01来算
                    if (mul < 0.01) {
                        mul = 0.01;
                    }
                }
            }
            //查询账户的余额
            BigDecimal myMoneys = BigDecimal.ZERO;
            UserEntity userEntity = userService.selectUserById(userId);
            if (type == 1) {
                myMoneys = userEntity.getBalance();
            } else {
                UserMoney userMoney = userMoneyDao.selectMoney(userId);
                myMoneys = userMoney.getMoney();
            }
            //扣除金额
            Double moneySum = AmountCalUtils.add(new BigDecimal(money), new BigDecimal(mul)).doubleValue(); //金额=提现金额+手续费
            if (myMoneys.doubleValue()>=moneySum) { //用户金额足够
                //扣除可提现金额直接在数据库进行操作
                //增加金额操作记录
                if (type == 1) {
                    userMoneyDao.updateUserBalance(userId, BigDecimal.valueOf(moneySum), 2);
                } else {
                    userCashOutDao.updateMoney(2, userId, moneySum);
                }

                UserMoneyDetails moneyDetails = new UserMoneyDetails();
                moneyDetails.setUserId(userId);
                moneyDetails.setShopId(shopId);
                moneyDetails.setTitle("提现：" + money);
                CashOut cashOut = new CashOut();
                String content;
                if (classify == 1) {
                    if (!"是".equals(isRate)) {
                        content = "支付宝提现：" + money;
                    } else {
                        content = "支付宝提现：" + money + "，扣除总金额：" + moneySum + "，手续费：" + mul;
                    }
                } else {
                    if (!"是".equals(isRate)) {
                        content = "微信提现：" + money;
                    } else {
                        content = "微信提现：" + money + "，扣除总金额：" + moneySum + "，手续费：" + mul;
                    }
                }
                cashOut.setCashQrCode(userEntity.getCashQrCode());
                moneyDetails.setContent(content);
                moneyDetails.setType(2);
                moneyDetails.setState(2);
                moneyDetails.setClassify(3);
                moneyDetails.setMoney(new BigDecimal(moneySum));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                moneyDetails.setCreateTime(sdf.format(new Date()));
                userMoneyDetailsDao.insert(moneyDetails);
                cashOut.setState(0);
                cashOut.setZhifubao(userEntity.getZhiFuBao());
                cashOut.setZhifubaoName(userEntity.getZhiFuBaoName());
                cashOut.setMoney(money.toString());
                cashOut.setCreateAt(sdf.format(new Date()));
                cashOut.setUserId(userId);
                cashOut.setRate(mul);
                cashOut.setOrderNumber(String.valueOf(System.currentTimeMillis()));
                cashOut.setClassify(classify);
                cashOut.setType(type);
                baseMapper.insert(cashOut);
                //扣除金额直接在数据库进行操作
                return Result.success("提现成功，将在三个工作日内到账，请耐心等待！");
            } else {
                return Result.error("金额不足，请输入正确的金额！");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("发起提现出错！" + e.getMessage(), e);
        } finally {
            reentrantReadWriteLock.writeLock().unlock();
        }
        return Result.error("系统繁忙，请稍后再试！");
    }

    @Override
    @Transactional
    public Result cashDepositMoney(Long userId) {
        //先判断用户是否通过实名认证
        UserEntity userEntity2 = userDao.selectById(userId);
        if ("0".equals(userEntity2.getCheckCertification())) {
            return Result.error("未通过实名认证，无法退保证金！");
        }
        //先判断骑手有没有未完成的订单
        List<TbIndent> indents = tbIndentDao.selectIndentList(userId);
        if (indents.size() > 0) {
            return Result.error("您有进行中的订单，无法退保证金！");
        }
        //判断骑手有没有被投诉订单
        List<ErrandComplaint> sysComplaints = complaintDao.selectComplaintList(userId);
        if (sysComplaints.size() > 0) {
            return Result.error("您有被投诉订单，请等待管理端审核后再退保证金！");
        }
        //将保证金退还到用户钱包
        UserEntity userEntity = userService.selectUserById(userId);
        UserEntity userEntity1 = new UserEntity();
        userEntity1.setUserId(userId);
        userEntity1.setCashDeposit(userEntity.getCashDeposit().subtract(userEntity.getCashDeposit()));
        userEntity1.setBalance(userEntity.getBalance().add(userEntity.getCashDeposit()));
        userService.updateById(userEntity1);
        //退保证金
        UserMoneyDetails userMoneyDetails = new UserMoneyDetails();
        userMoneyDetails.setMoney(userEntity.getCashDeposit());
        userMoneyDetails.setUserId(userId);
        userMoneyDetails.setContent("骑手退保证金：" + userEntity.getCashDeposit() + "元");
        userMoneyDetails.setTitle("骑手退保证金");
        userMoneyDetails.setType(1);
        userMoneyDetails.setState(2);
        userMoneyDetails.setClassify(3);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        userMoneyDetails.setCreateTime(simpleDateFormat.format(new Date()));
        userMoneyDetailsService.save(userMoneyDetails);

        UserMoneyDetails userMoneyDetails1 = new UserMoneyDetails();
        userMoneyDetails1.setMoney(userEntity.getCashDeposit());
        userMoneyDetails1.setUserId(userId);
        userMoneyDetails1.setContent("骑手退保证金：" + userEntity.getCashDeposit() + "元");
        userMoneyDetails1.setTitle("骑手退保证金");
        userMoneyDetails1.setType(2);
        userMoneyDetails1.setState(2);
        userMoneyDetails1.setClassify(1);
        userMoneyDetails1.setCreateTime(simpleDateFormat.format(new Date()));
        userMoneyDetailsService.save(userMoneyDetails1);

        return Result.success("保证金已退回到您的钱包");
    }

}
